layui.use(['form', 'table'], function(){
    var form = layui.form;
    var table = layui.table;

    form.on('checkbox(isAllProject)', function(data){
        let isChecked = data.elem.checked;
        if (isChecked) {
            $("#showAllProjectAuthForm").removeClass('hiddenForm');
            $("#nowProjectAuthAuthForm").addClass('hiddenForm');
        } else {
            $("#showAllProjectAuthForm").addClass('hiddenForm');
            $("#nowProjectAuthAuthForm").removeClass('hiddenForm');
        }
        $("#isAllReadProject").prop('checked', false);
        $("#isAllWriteProject").prop('checked', false);
        form.render('checkbox');
    });

    form.on('checkbox(apiSelectId)', function(data){
        var selectValue = data.value;
        var isChecked = data.elem.checked;
        if (selectValue == -1) {
            $('table input[type=checkbox]').each(function() {
                $(this).prop('checked', isChecked ? "checked" : '');
            });
        } else {
            var isAll = true;
            $('table input[type=checkbox]').each(function() {
                var obj = $(this);
                if (!obj.prop('checked') && obj.val() != -1) {
                    isAll = false;
                }
                $("#allApiList").prop('checked', isAll ? 'checked' : "");
            });
        }
        form.render('checkbox');
    });

    form.on('select(selectAllProjectList)', function (data) {
        resetAllForm();
        let projectId = data.value;
        let userId = $("#selectAllUserList").val();

        if (projectId > 0 && userId > 0) {
            let userAuth = getUserToProjectAuth(userId, projectId);
            if (userAuth === false) {
                throw new Error("获取当前用户权限失败");
                return false;
            }
            xrAllAuthForm(userAuth);
            xrAllApiList(projectId, 0, userAuth['projectAllCanSeeApiList']);
        }
    });

    form.on('select(selectAllUserList)', function (data) {
        resetAllForm();
        let userId = data.value;
        let projectId = $("#selectAllProjectList").val();

        if (projectId > 0 && userId > 0) {
            let userAuth = getUserToProjectAuth(userId, projectId);
            if (userAuth === false) {
                throw new Error("获取当前用户权限失败");
                return false;
            }
            xrAllAuthForm(userAuth);
            xrAllApiList(projectId, 0, userAuth['projectAllCanSeeApiList']);
        }
    });
    
    function resetAllForm() {
        $("#isAllProject").prop('checked', false);
        $("#isAllReadProject").prop('checked', false);
        $("#isAllWriteProject").prop('checked', false);
        $("#isWriteProject").prop('checked', false);
        $("#isReadProject").prop('checked', false);
        $("#allApiList").prop('checked', false);
        $("#showAllProjectAuthForm").addClass('hiddenForm');
        $("#nowProjectAuthAuthForm").removeClass('hiddenForm');
        $("#showAllApiTable > tbody").empty();
        form.render();
    }

    function xrAllAuthForm(userAuth) {
        if (userAuth['isAllProjectManage'] == 1) {
            $("#isAllProject").prop('checked', true);
            $("#isAllReadProject").prop('checked', true);
            $("#showAllProjectAuthForm").removeClass('hiddenForm');
            $("#nowProjectAuthAuthForm").addClass('hiddenForm');
            if (userAuth['isAllProjectManageWrite'] == 1) {
                $("#isAllWriteProject").prop('checked', true);
            }
        }

        if (userAuth['isProjectManage'] == 1) {
            $("#isReadProject").prop('checked', true);
            $("#showAllProjectAuthForm").addClass('hiddenForm');
            $("#nowProjectAuthAuthForm").removeClass('hiddenForm');
            if (userAuth['isProjectManageWrite']) {
                $("#isWriteProject").prop('checked', true);
            }
        }

        form.render();
    }

    /**
     * 获取当前用户权限
     *
     * @param userId
     * @param projectId
     * @returns {string}
     */
    function getUserToProjectAuth(userId, projectId) {
        let url = getApiHttpUrl('api/projectauth/getuserprojectauth');
        let userAuth = "";
        HttpRequest.request({
            url:url,
            type:'POST',
            dataType:'JSON',
            data:{
                userId: userId,
                projectId: projectId
            },
            async:false,
            success:function (datas) {
                if (datas.status == "YES") {
                    userAuth = datas.data;
                } else {
                    userAuth = false;
                }
            },
            error:function (e) {
                userAuth = false;
                layer.msg("服务器开小差了~");
            }
        });
        return userAuth;
    }

    //获取所有选中框的值
    function getAllSelectId() {
        var arr_box = [];
        $('tbody input[type=checkbox]:checked').each(function() {
            arr_box.push($(this).val());
        });
        return arr_box;
    }

    //获取所有用户并渲染
    function xrAllUserList() {
        let url = getApiHttpUrl('api/user/getalluserlist');
        HttpRequest.request({
            url:url,
            type:'POST',
            dataType:'JSON',
            data:{},
            success:function (datas) {
                if (datas.status == "YES") {
                    xrUserListForm(datas.data);
                } else {
                    layer.msg(datas.info);
                }
            },
            error:function (e) {
                layer.msg("服务器开小差了~");
            }
        });
    }

    //渲染用户列表
    function xrUserListForm(data) {
        let htmlStr = "";
        for (let i in data) {
            htmlStr += '<option value="'+ data[i]['id'] +'">'+ data[i]['username'] +'</option>';
        }
        $("#selectAllUserList").append(htmlStr);
        form.render('select');
    }

    //获取所有项目并渲染
    function xrAllProjectList() {
        let url = getApiHttpUrl('api/projectauth/getallproject');
        HttpRequest.request({
            url:url,
            type:'POST',
            dataType:'JSON',
            data:{},
            success:function (datas) {
                if (datas.status == "YES") {
                    xrProjectListForm(datas.data);
                } else {
                    layer.msg(datas.info);
                }
            },
            error:function (e) {
                layer.msg("服务器开小差了~");
            }
        });
    }

    //渲染项目列表
    function xrProjectListForm(data) {
        let htmlStr = "";
        for (let i in data) {
            htmlStr += '<option value="'+ data[i]['id'] +'">'+ data[i]['name'] +'</option>';
        }
        $("#selectAllProjectList").append(htmlStr);
        form.render('select');
    }

    //获取所有接口列表并渲染
    function xrAllApiList(projectId, categoryId=0, projectAllCanSeeApiList) {
        let url = getApiHttpUrl('api/apidoc/getapidoclist');
        HttpRequest.request({
            url:url,
            type:'POST',
            dataType:'JSON',
            data:{
                projectId:projectId,
                categoryId:categoryId
            },
            success:function (datas) {
                if (datas.status == "YES") {
                    xrApiTable(datas.data, projectAllCanSeeApiList);
                } else {
                    layer.msg(datas.info);
                }
            },
            error:function (e) {
                layer.msg("服务器开小差了~");
            }
        });
    }

    //渲染接口列表
    function xrApiTable(data, projectAllCanSeeApiList) {
        let htmlStr = "";
        let allApiIdList = [];
        for (let i in data) {
            allApiIdList.push(data[i]['id']);
            htmlStr += '<tr>'+
                '<td><input type="checkbox" lay-filter="apiSelectId" value="'+ data[i]['id'] +'" lay-skin="primary" '+ (in_array(data[i]['id'], projectAllCanSeeApiList) ? "checked" : "") +'></td>'+
                '<td>'+ data[i]['title'] +'</td>'+
                '<td>'+ data[i]['url'] +'</td>'+
                '<td>'+ data[i]['categoryName'] +'</td>'+
                '</tr>';
        }

        if (projectAllCanSeeApiList.length > 0 && array_same(projectAllCanSeeApiList, allApiIdList)) {
            $("#allApiList").prop('checked', true);
        }
        $("#showAllApiTable > tbody").append(htmlStr);
        form.render('checkbox');
    }

    /**
     * 获取提交数据
     * @returns {{isAllProjectManage: number, isAllProjectManageWrite: number, isProjectManage: number, isProjectManageWrite: number, projectAllCanSeeApiList: string, userId: *, projectId: *}}
     */
    function getSubmitData() {
        let userId = $("#selectAllUserList").val();
        let projectId = $("#selectAllProjectList").val();
        let data = {
            userId:userId,
            projectId:projectId,
            isAllProjectManage:0,
            isAllProjectManageWrite:0,
            isProjectManage:0,
            isProjectManageWrite:0,
            projectAllCanSeeApiList:""
        };

        let isAllReadProject = $("#isAllReadProject").prop('checked') ? 1 : 0;
        let isAllWriteProject = $("#isAllWriteProject").prop('checked') ? 1 : 0;

        if (isAllReadProject == 1 || isAllWriteProject == 1) {
            isAllReadProject = 1;
            data.isAllProjectManage = isAllReadProject;
            data.isAllProjectManageWrite = isAllWriteProject;
            return data;
        }

        let isReadProject = $("#isReadProject").prop('checked') ? 1 : 0;
        let isWriteProject = $("#isWriteProject").prop('checked') ? 1 : 0;
        if (isReadProject == 1 || isWriteProject == 1) {
            isReadProject = 1;
            data.isProjectManage = isReadProject;
            data.isProjectManageWrite = isWriteProject;
            return data;
        }

        let allApiIdList = getAllSelectId();
        if (allApiIdList.length > 0) {
            data.projectAllCanSeeApiList =allApiIdList.toString();
        }

        return data;
    }

    /**
     * 提交权限
     */
    $("#submitAuthBtn").click(function () {
        let userId = $("#selectAllUserList").val();
        let projectId = $("#selectAllProjectList").val();
        if (userId * projectId == 0) {
            layer.msg("用户或项目不能为空");
            return false;
        }
        let data = getSubmitData();
        let url = getApiHttpUrl('api/projectauth/setuserprojectauth');
        HttpRequest.request({
            url:url,
            type:"POST",
            dataType:"JSON",
            data:data,
            success:function (datas) {
                layer.msg(datas.info);
            },
            error:function (e) {
                layer.msg("服务器开小差了~");
            }
        });
    });

    /**
     * 判断一个元素是否在数组中
     * @param key
     * @param arr
     * @returns {boolean}
     */
    function in_array(key, arr) {
        for (let i in arr) {
            if (arr[i] == key) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断两个数组是否相等
     * @param $arrOne
     * @param $arrTwo
     * @returns {boolean}
     */
    function array_same($arrOne, $arrTwo) {
        return $arrOne.sort().toString() === $arrTwo.sort().toString();
    }

    (() => {
        //初始化界面
        xrAllUserList();
        xrAllProjectList();
    })();
});